import axios from 'axios';
import { CreateDocumentRequest, Document, DocumentQuery, UpdateDocumentRequest } from '../types/document';

// API基础URL
const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:8080/api';

// 文档API
export const documentApi = {
  /**
   * 获取所有文档
   */
  getAll: async (params?: DocumentQuery) => {
    const response = await axios.get(`${API_BASE_URL}/documents`, { params });
    return response.data;
  },

  /**
   * 获取指定ID的文档
   */
  getById: async (id: number) => {
    const response = await axios.get(`${API_BASE_URL}/documents/${id}`);
    return response.data;
  },

  /**
   * 获取指定知识库ID的所有文档
   */
  getByKnowledgeBaseId: async (knowledgeBaseId: number, params?: Omit<DocumentQuery, 'knowledgeBaseId'>) => {
    const response = await axios.get(`${API_BASE_URL}/knowledge-bases/${knowledgeBaseId}/documents`, { params });
    return response.data;
  },

  /**
   * 上传文档
   */
  upload: async (file: File, knowledgeBaseId: number) => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('knowledgeBaseId', knowledgeBaseId.toString());

    const response = await axios.post(`${API_BASE_URL}/documents/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / (progressEvent.total || 1));
        // 可以在这里触发上传进度更新
        console.log(`上传进度: ${percentCompleted}%`);
      },
    });

    return response.data;
  },

  /**
   * 创建文档
   */
  create: async (data: CreateDocumentRequest) => {
    const response = await axios.post(`${API_BASE_URL}/documents`, data);
    return response.data;
  },

  /**
   * 更新文档
   */
  update: async (id: number, data: UpdateDocumentRequest) => {
    const response = await axios.put(`${API_BASE_URL}/documents/${id}`, data);
    return response.data;
  },

  /**
   * 删除文档
   */
  delete: async (id: number) => {
    const response = await axios.delete(`${API_BASE_URL}/documents/${id}`);
    return response.data;
  },

  /**
   * 获取文档处理状态
   */
  getStatus: async (id: number) => {
    const response = await axios.get(`${API_BASE_URL}/documents/${id}/status`);
    return response.data;
  },

  /**
   * 搜索文档
   */
  search: async (query: string, params?: Omit<DocumentQuery, 'searchTerm'>) => {
    const response = await axios.get(`${API_BASE_URL}/documents/search`, {
      params: {
        ...params,
        query,
      },
    });
    return response.data;
  },
}; 